﻿using System;
using System.Windows;
using System.Windows.Controls;
using SmartSpace.Silverlight;
using System.Windows.Browser;
using SmartSpace.Silverlight.Shell.ServiceRef;

namespace SmartSpace.Silverlight.Shell
{
    public partial class RootPage : UserControl
    {
        private static RootPage s_rootPage;

        public static RootPage Instance
        {
            get
            {
                if (s_rootPage == null)
                {
                    s_rootPage = new RootPage();
                }
                return s_rootPage;
            }
        }

        private RootPage()
        {
            InitializeComponent();

            m_viewContainer.SwitchEffect = new FadeSwitchEffect();

            this.Loaded += new RoutedEventHandler(OnRootPageLoaded);
        }

        void OnRootPageLoaded(object sender, RoutedEventArgs e)
        {
            // 检查是否已经登录
            SlWebServiceSoapClient coreService = App.CreateSlWebServiceProxy();
            coreService.CheckAuthenticatedCompleted += new EventHandler<CheckAuthenticatedCompletedEventArgs>(OnCheckAuthenticatedCompleted);
            coreService.CheckAuthenticatedAsync();
        }

        void OnCheckAuthenticatedCompleted(object sender, CheckAuthenticatedCompletedEventArgs e)
        {
            if (e.Result.IsSuccess)
            {
                AppData.User = new SlUser();
                AppData.User.Account = e.Result.Data.Account;
                AppData.User.Name = e.Result.Data.Name;
                //AppData.User.Email = e.Result.Data.Email;
                //AppData.User.Phone = e.Result.Data.Phone;
                this.SwitchView(new LoadingView());
            }
            else
            {
                HtmlPage.Window.Navigate(new Uri((App.Current as SlApp).Params.AppUrl + "Login.aspx"));
                //this.SwitchView(new LoginView());
            }
        }

        public void SwitchView(SlView view)
        {
            m_viewContainer.SwitchView(view);
        }
    }
}
